import React from 'react';
import { Form, Input, Modal, Button, Cascader } from 'antd';
import PropTypes from 'prop-types';
import { arrayToTree } from 'utils';
// import { connect } from 'dva/router';

const FormItem = Form.Item;
const { TextArea } = Input;

@Form.create()
class CreateForm extends React.Component {
  static propTypes = {
    form: PropTypes.object.isRequired,
    visible: PropTypes.bool.isRequired,
    handleCancel: PropTypes.func.isRequired,
    handleSubmit: PropTypes.func.isRequired,
    depts: PropTypes.array.isRequired,
  }

  _handleSubmit = () => {
    const { handleSubmit, handleCancel, form: { validateFieldsAndScroll, resetFields } } = this.props;
    validateFieldsAndScroll((err, values) => {
      // console.log(values);
      if (!err) {
        // console.log('Received values of form: ', values);
        handleSubmit(values);
        resetFields();
        handleCancel();
      }
    });
  }

  _generateDeptOptions = () => {
    const { depts } = this.props;
    const newDepts = depts.map(_ => ({
      key: _.ID,
      value: _.ID,
      label: _.Name,
      pid: _.ParentID,
      treePath: _.TreePath,
    }));
    const deptTrees = arrayToTree(newDepts, 'value', 'pid', 'children');

    const options = [
      {
        value: '',
        label: '无上级部门',
      },
      ...deptTrees,
    ];

    return options;
  }

  _handleSelectChange = () => {

  }

  render () {
    const {
      visible,
      form: {
        getFieldDecorator,
      },
      handleCancel,
    } = this.props;

    const options = this._generateDeptOptions();

    return (
      <Form>
        <Modal
          title={'新增部门'}
          visible={visible}
          onOk={this._handleSubmit}
          onCancel={handleCancel}
          footer={
            [
              <Button key="cancel" onClick={handleCancel}>取消</Button>,
              <Button key="submit" type="primary" onClick={this._handleSubmit}>提交</Button>,
            ]
          }
        >
          <FormItem
            label="部门名"
          >
            {
              getFieldDecorator('name', {
                rules: [{ required: true, message: '请输入部门名称', whitespace: true }],
              })(<Input />)
            }
          </FormItem>

          <FormItem
            label="上级部门"
          >
            {
              getFieldDecorator('parentID', {
                rules: [{ required: true, type: 'array', message: '请选择上级部门', whitespace: true }],
              })(<Cascader options={options} changeOnSelect />)
            }
          </FormItem>

          <FormItem
            label="部门说明"
          >
            {
              getFieldDecorator('description', {
                rules: [{ required: false }],
              })(<TextArea rows={4} />)
            }
          </FormItem>
        </Modal>
        
      </Form>
    )
  }
}

export default CreateForm;
